package robotAPI;

import javax.xml.parsers.*;
import org.xml.sax.InputSource;
import org.w3c.dom.*;
import java.io.*;

public class ParseXMLString {

	public RobotReplyMessage parse(String xmlstring) {
		// String xmlstring =
		// "<r2s> <scan n=\"2\" n1=\"15\" n2=\"13\"/> <move req=\"3\" real=\"3\"/> <rotate req=\"3\" real=\"4\"/> <reboot/> <GXsomething>5</GXsomething></r2s>";
		int mReal, mReq, rReal, rReq, nScan;
		boolean reboot;
		int scanValues[];

		try {
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = dbf.newDocumentBuilder();

			InputSource is = new InputSource();
			is.setCharacterStream(new StringReader(xmlstring));

			Document doc = db.parse(is);
			NodeList nodes = doc.getElementsByTagName("r2s");
			Element message = (Element) nodes.item(0);

			/* Get movement information */
			NodeList move = message.getElementsByTagName("move");
			Element moveField = (Element) move.item(0);
			if (move.getLength() > 0 && moveField.hasAttribute("req")
					&& moveField.hasAttribute("real")) {
				mReal = Integer.parseInt(moveField.getAttribute("real"));
				mReq = Integer.parseInt(moveField.getAttribute("req"));
			} else {
				mReal = 0;
				mReq = 0;
			}

			/* Get rotation information */
			NodeList rotate = message.getElementsByTagName("rotate");
			Element rotateField = (Element) rotate.item(0);

			if (rotate.getLength() > 0 && rotateField.hasAttribute("req")
					&& rotateField.hasAttribute("real")) {
				rReal = Integer.parseInt(rotateField.getAttribute("real"));
				rReq = Integer.parseInt(rotateField.getAttribute("req"));
			} else {
				rReal = 0;
				rReq = 0;
			}

			/* Get scan information */
			NodeList scan = message.getElementsByTagName("scan");
			Element scanField = (Element) scan.item(0);
			if (scan.getLength() > 0 && scanField.hasAttribute("n")) {
				nScan = Integer.parseInt(scanField.getAttribute("n"));
				scanValues = new int[nScan];
				for (int i = 0; i < nScan; i++) {
					scanValues[i] = Integer.parseInt(scanField.getAttribute("n"
							+ (i + 1)));
				}
			} else {
				scanValues = null;
				nScan = 0;
			}

			/* Get reboot information */
			NodeList reb = message.getElementsByTagName("reboot");
			if (reb.getLength() == 0) {
				reboot = false;
			} else {
				reboot = true;
			}

			RobotReplyMessage msg = new RobotReplyMessage(mReq, mReal, rReq,
					rReal, nScan, scanValues, reboot);
			System.out.println(msg);
			return msg;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	public static String getCharacterDataFromElement(Element e) {
		Node child = e.getFirstChild();
		if (child instanceof CharacterData) {
			CharacterData cd = (CharacterData) child;
			return cd.getData();
		}
		return "?";
	}
}